#include "playimageswidget.h"
#include <QPainter>
#include <QDir>
#include <QFileInfo>
#include <QCollator>
#include <QDebug>

PlayImagesWidget::PlayImagesWidget(QString dir, QWidget *parent)
    : QWidget(parent)
    , m_imgDir(dir)
    , m_curIndex(0)
    , m_frameRate(16)
    , m_loop(false)
    , m_scale(1.0)
{
    m_timer = new QTimer(this);
    connect(m_timer, SIGNAL(timeout()), this, SLOT(updateIndex()));

    loadImages(dir);
}

PlayImagesWidget::~PlayImagesWidget()
{

}

void PlayImagesWidget::setImageDir(const QString &dir)
{
    if (m_imgDir == dir)
        return;

    loadImages(dir);
    m_imgDir = dir;
}

void PlayImagesWidget::setLoopPlay(bool loop)
{
    m_loop = loop;
}

void PlayImagesWidget::setScale(qreal scale)
{
    if (qFuzzyCompare(m_scale, scale))
        return;

    m_scale = scale;
    QSize size = this->size();
    this->setFixedSize(size * m_scale);
}

void PlayImagesWidget::play(int frameRate)
{
    if (m_imgList.isEmpty())
        return;

    if (frameRate != 0 && frameRate != m_frameRate) {
        m_frameRate = frameRate;
    }

    m_timer->start(1000 / m_frameRate);
    this->update();
}

void PlayImagesWidget::stop()
{
    m_timer->stop();
}

void PlayImagesWidget::loadImages(const QString &dir)
{
    QDir imgDir(dir);
    QFileInfoList infoList = imgDir.entryInfoList(QDir::Files | QDir::NoDotAndDotDot, QDir::Name);
    if(infoList.isEmpty()){
        qWarning() << "Image dir is empty: " << dir;
        return;
    }

    // 对字符串进行排序，(避免出现1.txt 10.txt 11.txt 2.txt.20.txt....)
    QCollator collator;
    collator.setNumericMode(true);
    std::sort(infoList.begin(), infoList.end(), [&collator](const QFileInfo &info1, const QFileInfo &info2){
        return collator.compare(info1.filePath(), info2.filePath()) < 0;
    });

    m_imgList.clear();
    for (auto info : infoList) {
        m_imgList.append(QPixmap(info.filePath()));
    }

    this->setFixedSize(m_imgList.first().size());
    qDebug() << "load image size:" << m_imgList.length();
}

void PlayImagesWidget::updateIndex()
{
    if (m_curIndex < 0) {
        m_curIndex = 0;
    }

    if (m_curIndex >= m_imgList.length() - 1) {
        if (m_loop ) {
            m_curIndex = 0;
        } else {
            this->stop();
            return;
        }
    }

    ++m_curIndex;
    this->update();
}

void PlayImagesWidget::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);
    QPainter painter(this);

    if (m_curIndex < m_imgList.length() && m_curIndex >= 0) {
        painter.drawPixmap(rect(), m_imgList.at(m_curIndex));
    }
}
